package com.glela.controller;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.glela.api.upload.qiniu.general.QiniuUtils;
import com.glela.cache.redis.RedisUtil;
import com.glela.common.constant.CommonConstants;
import com.glela.common.util.OrderUtil;
import com.glela.goods.mapper.InventoryMapper;
import com.glela.goods.model.GoodsPrice;
import com.glela.goods.model.Inventory;
import com.glela.goods.service.GoodsService;
import com.glela.goods.service.InventoryService;
import com.glela.mq.service.OrderQueueService;
import com.glela.order.mapper.OrderTokenMapper;
import com.glela.order.model.OrderDetail;
import com.glela.order.model.OrderToken;
import com.glela.order.model.request.RequestOrderDetail;
import com.glela.platform.constant.ErrorEnum;
import com.glela.platform.mapper.UserMapper;
import com.glela.platform.model.User;
import com.glela.platform.model.request.RequestVersionModel;
import com.glela.platform.model.response.ResponseBaseModel;
import com.glela.platform.model.response.ResponseResultModel;
import com.glela.platform.service.BaseRestrictionsService;
import com.glela.platform.service.UserService;
import com.glela.platform.service.VersionService;
import com.glela.platform.util.ParameterUtils;
import com.glela.serial.model.request.RequestSerial;
import com.glela.serial.service.SerialGoodService;

@Controller
@RequestMapping("/test")
public class testRedisController {
	private static Logger			logger			= LoggerFactory.getLogger(testRedisController.class);
	
	@Autowired
	private BaseRestrictionsService baseRestrictionsService;
	
	@Autowired
	private GoodsService goodsService;
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private OrderTokenMapper orderTokenMapper;
	
	
	@Autowired
	private SerialGoodService serialGoodService;
	
	
	@Autowired
	private InventoryService inventoryService;
	
	
	@Autowired
	private InventoryMapper inventoryMapper;
	
	@Autowired
	private OrderQueueService orderQueueService;
	
	@Autowired
	private RedisUtil redisUtil;
	
	
	
	
	@RequestMapping("testaddredis")
	public @ResponseBody ResponseEntity<?> testaddredis(@RequestBody JSONObject json){
		Map<String,Object> _map = new HashMap<String,Object>();
		
		try {
			
			User u = new User();
			
			u.setUserName("33fffff");
			u.setPassword("34534534534");
			u.setCreateTime("2017-02-02 01:02:32");
			u.setRoleId(2);
			u.setBindRecommendMode(1);
			u.setRecommendFrom("FD45522121");
			u.setTalentTeacher("44444");
			
			
			
			
			String tests = "13598008451";
			
			for(String s : tests.split(",")) {
				userService.updateUserCacheByUserName(s);
				userService.cacheUserPersionByUserByUserName(s);
			}
			
			
			
			User us = userService.getUserById(248L);
			System.out.println("1----------------------" + us.getNickName());
			
			
			User pus = userService.getUserByPersionId(us.getRecommendFrom());
			System.out.println("2----------------------" + us.getNickName());
			
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
		return new ResponseEntity<>(new ResponseResultModel<>(_map), HttpStatus.OK);
	}
	
	
	
	
	@RequestMapping("addinventory")
	public @ResponseBody ResponseEntity<?> addinventory(@RequestBody JSONObject json){
		Map<String,Object> _map = new HashMap<String,Object>();
		
		Long _id = 3153l;
		
		
		Inventory _inventory = inventoryMapper.selectByPrimaryKey(_id);
		
		try {
			inventoryService.updateInventory(_inventory.getId(), 100);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
		return new ResponseEntity<>(new ResponseResultModel<>(_map), HttpStatus.OK);
	}
	
	
	
	@RequestMapping("test_redis")
	public @ResponseBody ResponseEntity<?> testRedis(@RequestBody JSONObject json){
		GoodsPrice v;
		//BaseRestrictions b = baseRestrictionsService.getBaseRestrictionsForCache("xz_jj");
		// type : 1 PRODUCT ,2 GOODSID
		if (ParameterUtils.validParams( json.getString("productId"), json.getString("type") )) {
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
		}
		User user = null ;
		if(!StringUtils.isBlank(json.getString("userId"))) {
			userMapper.selectByPrimaryKey(Long.valueOf(json.getString("userId")));
		}
		if(json.getString("type").equals("1")) {
			v = goodsService.getGoodsViewPriceForProduct(user, Long.valueOf(json.getString("productId")));
			
		}else {
			v = goodsService.getGoodsViewPriceForGoods(user, Long.valueOf(json.getString("productId")));
		}
		
		return new ResponseEntity<>(new ResponseResultModel<>(v), HttpStatus.OK);
	}
	
	
	
	@Resource
	private VersionService versionService;
	
	@RequestMapping(value = "/getVersionInfo", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> getVersionInfo(@RequestBody RequestVersionModel reVersion) {
		try {
			
			long uid = 671546;
			long begin1 = new Date().getTime();
			User u1 = userMapper.selectRecommendFromByUserId(uid);
			logger.error("�ɵ���ʱ: {} : {}", (new Date().getTime() - begin1 ), u1 == null ? "9999999" : u1.getId());
			long begin2 = new Date().getTime();
			User u2 = userService.selectRecommendFromByUserId(uid);
			
			logger.error("�µ���ʱ: {} : {}", (new Date().getTime() - begin2 ) , u2 == null ? "9999999" : u1.getId());
			
			
			return null;
		} catch (Exception e) {
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}
	
	
	
	@RequestMapping("getGooodPrice")
	public @ResponseBody ResponseEntity<?> getGooodPrice(@RequestBody JSONObject json){
		GoodsPrice v;
		if (ParameterUtils.validParams( json.getString("goodsId"), json.getString("limitSaleId") )) {
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
		}
		User user = null ;
		if(!StringUtils.isBlank(json.getString("userId"))) {
			user = userMapper.selectByPrimaryKey(Long.valueOf(json.getString("userId")));
		}
		
		v = goodsService.getGoodsViewPriceForGoods(user, Long.valueOf(json.getString("goodsId")) , Long.valueOf(json.getString("limitSaleId")));
		return new ResponseEntity<>(new ResponseResultModel<>(v), HttpStatus.OK);
	}
	
	
	@RequestMapping(value = "/addorderinfos", method = RequestMethod.POST)
	@ResponseBody
	public ResponseEntity<?> addOrderInfos(@RequestBody String userName) {
		try {
			RequestOrderDetail reqOrderDetail = new RequestOrderDetail();
			reqOrderDetail.setPayType(22);
			reqOrderDetail.setCashCoin(332);
			List<OrderDetail> odl = new ArrayList<OrderDetail>();
			OrderDetail od = new OrderDetail();
			od.setGoodId(222L);
			od.setProductId(2343L);
			od.setCashCoin(32423);
			od.setBrandName("����Ʒ��");
			
			odl.add(od);
			reqOrderDetail.setOrderDetailList(odl);
			
			
			String odtail = "";
			
			odtail = "";
			
			StringBuffer orderSn = new StringBuffer();
			orderSn.append(CommonConstants.ORDER_OBJECT_PREFIX).append(OrderUtil.getOrderSn());
			reqOrderDetail.setParentOrderSn(orderSn.toString());
			//orderQueueService.createOrder("452453425234dfgsfdgsdfgsdf");
			
			//orderQueueService.addCommision(orderSn);
			
			return null;
			
		}catch(Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	
	@RequestMapping("getGooodPrices")
	public @ResponseBody ResponseEntity<?> getGooodPrices(@RequestBody JSONObject json) {
		// 248
		User user = userMapper.selectByPrimaryKey(6497l);
		List<Long> plist = new ArrayList<Long>();
//		plist.add(2058l);
//		plist.add(122l);
//		plist.add(100l);
//		plist.add(654l);
//		plist.add(786l);
//		plist.add(267l);
//		plist.add(1512l);
//		plist.add(514l);
//		plist.add(644l);
//		plist.add(1871l);
//		plist.add(1591l);
//		plist.add(1929l);
//		plist.add(619l);
//		plist.add(814l);
//		plist.add(1790l);
//		plist.add(1847l);
//		plist.add(2059l);
//		plist.add(1882l);
//		plist.add(1965l);
//		plist.add(1574l);
//		plist.add(1782l);
//		plist.add(751l);
//		plist.add(1938l);
//		plist.add(674l);
//		plist.add(1357l);
//		plist.add(1354l);
//		plist.add(1347l);
//		plist.add(799l);
//		plist.add(738l);
//		plist.add(1977l);
//		plist.add(1960l);
//		plist.add(812l);
//		plist.add(2086l);
//		plist.add(2140l);
//		plist.add(1957l);
//		plist.add(1955l);
//		plist.add(1848l);
//		plist.add(2089l);
//		plist.add(2128l);
//		plist.add(2063l);
//		plist.add(1356l);
//		plist.add(1349l);
//		plist.add(808l);
//		plist.add(795l);
//		plist.add(720l);
				
		plist.add(2333l);
//		plist.add(2171l);
//		plist.add(2058l);
//		plist.add(1977l);
//		plist.add(1972l);
//		plist.add(1938l);
//		plist.add(1864l);
//		plist.add(1459l);
//		plist.add(1458l);
//		plist.add(1456l);
//		plist.add(1355l);
//		plist.add(814l);
//		plist.add(801l);
//		plist.add(638l);
//		plist.add(2365l);
//		plist.add(2281l);
//		plist.add(2171l);
//		plist.add(1774l);
//		plist.add(1355l);
//		plist.add(801l);
//		plist.add(747l);
//		plist.add(638l);
//		plist.add(2058l);
		
		
		Map<Long,GoodsPrice> vlist = goodsService.getGoodsViewPriceForGoods(user, plist);
		return new ResponseEntity<>(new ResponseResultModel<>(vlist), HttpStatus.OK);
	}
	
	
	
	
	@RequestMapping("getOrderToken")
	public @ResponseBody ResponseEntity<?> getOrderToken(@RequestBody JSONObject json){
		OrderToken token = new OrderToken();
		token.setOrderKey("999999999");
		List<OrderToken> list = orderTokenMapper.selectAll(token);
		return new ResponseEntity<>(new ResponseResultModel<>(list), HttpStatus.OK);
	}
	
	
	
	
	@RequestMapping("getGooodPricesbatch")
	public @ResponseBody ResponseEntity<?> getGooodPricesbatch(@RequestBody JSONObject json) {
		
		User user = userMapper.selectByPrimaryKey(248l);
		List<Long> plist = new ArrayList<Long>();
		plist.add(133l);
		plist.add(523l);
		plist.add(519l);
		plist.add(797l);
		plist.add(1362l);
		plist.add(1611l);
		plist.add(1586l);
		plist.add(1430l);
		plist.add(1828l);
		plist.add(1447l);
		plist.add(1441l);
		plist.add(1635l);
		
		Map<Long,GoodsPrice> vlist = goodsService.getGoodsViewPriceForGoodsLimitTimeSale(user,33, plist);
		return new ResponseEntity<>(new ResponseResultModel<>(vlist), HttpStatus.OK);
	}
	
	
	
	//queryAllProductIdsBySerialIdForCache
	@RequestMapping("getserialLists")
	public @ResponseBody ResponseEntity<?> getserialLists(@RequestBody RequestSerial req) {
		 //return serialGoodService.queryAllProductIdsBySerialIdForCache(req);
		return null;
	}

	@RequestMapping("uploadImg")
	public String uploadImg(){
		try {
			FileInputStream in = new FileInputStream("D:\\111.jpg");
			byte[] data = toByteArray(in);
			in.close();
			String imgurl = QiniuUtils.uploadByBytys64("file/share/shareList/", data, "jpg");
			System.out.println(imgurl);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}

	private byte[] toByteArray(InputStream in) throws IOException {

		ByteArrayOutputStream out = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024 * 4];
		int n = 0;
		while ((n = in.read(buffer)) != -1) {
			out.write(buffer, 0, n);
		}
		return out.toByteArray();
	}


	@RequestMapping("/sendMessage")
	public String sendMessage() throws Exception {
		Map<String,Object> params = new HashMap<String, Object>();
		params.put("orderSn","123123123");
		orderQueueService.openStoreDone(params);
		return "success";
	}
}
